package com.ocom.ugcapi.mq.product;

import com.ocom.amqp.builder.CurrentLimitingQueueBuilder;
import com.ocom.amqp.core.CurrentLimitingQueue;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Description: 限流
 * @Author: 朱晖
 * @Date: 2022年7月12日09:02:39
 **/
@Component
public class CallbackProducer {

	@Resource
	private RabbitTemplate rabbitTemplate;

	@Resource
	CurrentLimitingQueueBuilder currentLimitingQueueBuilder;

//	@Resource
//	private CurrentLimitingQueue currentLimitingQueue;

	public void sendLimitingMessage(String body) {
		MessageProperties messageProperties = new MessageProperties();

		CurrentLimitingQueue currentLimitingQueue = new CurrentLimitingQueue(
				"callback"
				,"charge",
				300,
				1000l
		);
		currentLimitingQueueBuilder.build(currentLimitingQueue);

		System.out.println(currentLimitingQueue.getSendExchangeName());
		System.out.println(currentLimitingQueue.getRoutingKey());
		System.out.println(currentLimitingQueue.getCurrentLimiter());

		//1.将发送到哪个交换机设置到 消息的properties中
		messageProperties.setReceivedExchange(currentLimitingQueue.getSendExchangeName());

		//2.将路由键设置到 消息的properties中
		messageProperties.setReceivedRoutingKey(currentLimitingQueue.getRoutingKey());

		messageProperties.setContentType(MediaType.TEXT_PLAIN_VALUE);
//		String body = "限流消息";
		Message message = new Message(body.getBytes(), messageProperties);

		//3.获取限流队列的 限流器
		CurrentLimitingQueue.CurrentLimiter currentLimiter = currentLimitingQueue.getCurrentLimiter();

		//4.发送消息
		this.rabbitTemplate.convertAndSend(
				currentLimitingQueue.getSendExchangeName(),
				currentLimitingQueue.getRoutingKey(),
				message, currentLimiter);
	}
}